import axios from 'axios';
import RNFetchBlob from 'rn-fetch-blob';
import {BaseHost} from './apiPath';

const axiosInstance = axios.create({
  baseURL: BaseHost,
  timeout: 5000,
});

axiosInstance.interceptors.request.use(
  config => {
    console.log('req url', config.url);
    console.log('req data', config.data);
    if (global.user.userData) {
      config.headers['Authorization'] = global.user.userData.sessionId;
      config.headers['withCredentials'] = true;
    }
    console.log('header:', config.headers);

    return config;
  },
  error => {
    return Promise.reject(error);
  },
);

axiosInstance.interceptors.response.use(
  response => {
    console.log('res data---', response.data);
    if (response.data) {
      return response.data;
    }

    return Promise.resolve(response.data);
  },
  error => {
    const msg = error.response.data.msg || '请求失败';

    return Promise.reject(error);
  },
);

export const getUrl = path => {
  let url = global.server.url + path;
  return url;
};
// param 数组[{name:'',data:''}]
export const uploadFile = (param, path, callback) => {
  let url = getUrl(path);
  let headers = {
    'Content-Type': 'multipart/form-data',
  };
  if (global.user.userData) {
    headers['Authorization'] = global.user.userData.sessionId;
    headers['withCredentials'] = 'true';
  }

  RNFetchBlob.fetch('POST', url, headers, param)
    .then(resp => {
      const data = JSON.parse(resp.data);
      console.log('resp:', data);
      if (data.error) {
        throw data.error;
      }
      return data;
    })
    .then(res => {
      // console.log(' upload success:', res);
      callback({
        success: true,
        data: getUrl('/images/' + res.obj),
      });
    })
    .catch(err => {
      console.log(' upload error:', err);
      callback({
        success: false,
        errorInfo: err,
      });
    });
};

export default axiosInstance;
